import axios from "axios";
import { BASE_URL, TIMEOUT } from "./config";
import store from "../store";

const instance = axios.create({
  baseURL: BASE_URL,
  method: "post",
  timeout: TIMEOUT,
});

//添加拦截
instance.interceptors.request.use(
  (config) => {
    const token = JSON.parse(localStorage.getItem("userInfo"))?.token;
    if (token) {
      config.headers = {
        Authorization: "bearer " + token,
      };
    }
    return config;
  },
  (error) => {
    return Promise.reject(error)
  }
);

instance.interceptors.response.use(
  (res) => {
    return res.data;
  },
  (error) => {
    if (error.response?.status === 401) {
      store.dispatch({ type: "logout" });
    }
    return Promise.reject(error);
  }
);

export default instance;
